package com.joro.ejb;

import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.app.LoggingUtil;
import com.joro.Customer;
import com.joro.Magazine;

/**
 * Session Bean implementation class CustomerFacade
 */
@Stateless
public class CustomerFacade implements CustomerFacadeLocal {
	@PersistenceContext(unitName = "magazine.ejb")
	EntityManager manager;

    /**
     * Default constructor. 
     */
    public CustomerFacade() {
        // TODO Auto-generated constructor stub
    }

	@Override
	public Collection<Customer> getCustomers() {
		Query query = manager.createQuery("SELECT e FROM Customer e");
		List<Customer> resultList = query.getResultList();
		return resultList;
	}

	@Override
	public void deleteCustomer(Customer customer) {
		LoggingUtil.logOperation(LoggingUtil.OPERATION_DELETE, customer);
		manager.remove(manager.contains(customer) ? customer : manager.merge(customer));
	}

	@Override
	public Customer getCustomerById(int customerId) {
		Query query = manager.createQuery("SELECT e FROM Customer e WHERE e.id = ?1");
		query.setParameter(1, customerId);
		List<Customer> resultList = query.getResultList();
		if( !resultList.isEmpty()){
			return resultList.get(0);
		}
		return null;
	}

	@Override
	public void saveCustomer(Customer customer) {
		LoggingUtil.logOperation(LoggingUtil.OPERATION_UPDATE, customer);
		manager.merge(customer);
	}

}
